import plugin from '../../../lib/plugins/plugin.js'
import fetch from "node-fetch"
import Config from "../models/Config.js"

const temp = {}
const reminder = "没有这个乐子，如果你有提交到 https://gitee.com/huifeidemangguomao/liulian-GroupFriendsClassicspeech"

export class 乐 extends plugin {
  constructor() {
    super({
      name: "小月-乐子",
      dsc: "乐",
      event: "message",
      priority: 9999,
      rule: [
        {
          reg: "^#查看乐子人$",
          fnc: "show"
        },
        {
          reg: "^#查看乐子人.+别名$",
          fnc: "showAlias"
        },
        {
          reg: "^#查看乐子人.+有多少图$",
          fnc: "showCount"
        },
        {
          reg: "^#查看乐子.+$",
          fnc: "random"
        }
      ]
    })
  }

  async fetch(url) {
    const class_url = Config.getConfig().class_url
    try {
      return (await fetch(`${class_url}/${url}`)).json()
    } catch (err) {
      this.reply(`出错了\n${err?.stack || err}`, true)
      throw err
    }
  }

  async cache(url) {
    if (temp[url] && (Date.now() - temp[url].time < 3600000))
      return temp[url].res
    temp[url] = {
      res: await this.fetch(url),
      time: Date.now(),
    }
    return temp[url].res
  }

  async show() {
    if (!Config.getConfig().class) return false
    const res = await this.cache("?list=all&type=alias")
    return this.reply(await this.makeForwardMsg("乐子人列表：", Object.keys(res).reduce((acc, cur, index) => {
      const chunkIndex = Math.floor(index / 10)
      if (!acc[chunkIndex]) {
        acc[chunkIndex] = `${index + 1}.${cur}`
      } else {
        acc[chunkIndex] += `\n${index + 1}.${cur}`
      }
      return acc
    }, [])))
  }

  async showAlias() {
    if (!Config.getConfig().class) return false
    const msg = this.e.msg.match(/^#查看乐子人(.+)别名$/)[1]
    const res = await this.cache("?list=all&type=alias")
    if (!res[msg]) return this.reply(reminder)
    return this.reply(`- ${res[msg].join("\n- ")}`, true)
  }

  async showCount() {
    if (!Config.getConfig().class) return false
    const msg = this.e.msg.match(/^#查看乐子人(.+)有多少图$/)[1]
    const res = await this.cache("?list=all")
    if (!res.resources[msg]) return this.reply(reminder)
    return this.reply(String(res.resources[msg]), true)
  }

  async random() {
    if (!Config.getConfig().class) return false
    const msg = this.e.msg.replace("#查看乐子", "")
    const res = await this.fetch(`?list=${msg === "图" ? "sj" : msg}&type=alias`)
    if (res.code !== 0) {
      if (res.msg)
        return this.reply(res.msg)
      else
        return false
    }
    return this.reply(segment.image(res.url))
  }

  async makeForwardMsg(title, msg, end) {
    let nickname = (this.e.bot ?? Bot).nickname
    let userInfo = {
      user_id: (this.e.bot ?? Bot).uin,
      nickname
    }
    let forwardMsg = [
      {
        ...userInfo,
        message: title
      }
    ]
    for (const message of msg) {
      if (!message) {
        continue
      }
      forwardMsg.push({
        ...userInfo,
        message: message
      })
    }
    if (end) {
      forwardMsg.push({
        ...userInfo,
        message: end
      })
    }
    if (this.e.group?.makeForwardMsg) {
      forwardMsg = await this.e.group.makeForwardMsg(forwardMsg)
    } else if (this.e?.friend?.makeForwardMsg) {
      forwardMsg = await this.e.friend.makeForwardMsg(forwardMsg)
    } else {
      return msg.join('\n')
    }
    let dec = 'xiaoyue-plugin'
    if (typeof (forwardMsg.data) === 'object') {
      let detail = forwardMsg.data?.meta?.detail
      if (detail) {
        detail.news = [{ text: dec }]
      }
    } else {
      forwardMsg.data = forwardMsg.data
        .replace(/\n/g, '')
        .replace(/<title color="#777777" size="26">(.+?)<\/title>/g, '___')
        .replace(/___+/, `<title color="#777777" size="26">${dec}</title>`)
    }
    return forwardMsg
  }
}